import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {getPage, update,del} from './service';
import "./index.css";
import {Button, Image, Input, message, Modal, Select, Upload} from "antd";
import Access from "@/components/Access/Access";
import {PlusOutlined} from "@ant-design/icons";
import CreateForm from "./components/CreateForm";
import styles from "@/global.less";

import defaultSetting from '@/../config/defaultSettings';

const {baseUrl} = defaultSetting;
const TableList = (props) => {
  const actionRef = useRef();
  const [count, setCount] = useState();
  const [createModalVisible, handleModalVisible] = useState(false);
  const [formValues, setFormValues] = useState({});
  const [fileList, handleFileList] = useState([]);

  useEffect(() => {
  }, []);
  const handlePayUploadChange = (info) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'error') {
      message.error("文件上传失败");
      return;
    }
    if (info.file.status === 'done'){
      fileList.push({
        uid:info.file.response.data.fileName,
        status: 'done',
        url:info.file.response.data.url
      });
      handleFileList(fileList);
    }
  };
  const handleRemove = (file)=>{
    let id = file.response?file.response?.data.fileName:file.uid;
    handleFileList(fileList.filter(file=>file.uid !== id));
  };
  const columns = [

    {
      title: '名称',
      dataIndex: 'imgName',
      hideInSearch:true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称必填项',
          },
        ],
      },
    },
    {
      title: '商品条码',
      dataIndex: 'barCode',
      hideInSearch:true,
      hideInTable:true
    },
    {
      title: '序号',
      dataIndex: 'imgSort',
      hideInSearch:true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '序号必填项',
          },
        ],
      },
    },
    {
      title: '轮播图',
      dataIndex: 'option',
      hideInSearch:true,
      renderFormItem: () => {
        return (
          <Upload
            name="file"
            action={() => {
              return `${baseUrl}wmp/index/upload`;
            }}
            listType="picture-card"
            defaultFileList={fileList}
            onChange={handlePayUploadChange}
            onRemove={handleRemove}
            headers={{token: sessionStorage.getItem('token'), type: 'ADMIN'}}
          >
            <PlusOutlined/>
          </Upload>
        );
      },
      render: (_, payload) => {
        return <><Image className={styles.img_div} src={payload.img} /></>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => {
        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              <Access accessKey={"@approved_update"}>
                <Button
                  type="primary"
                  style={{
                    marginLeft: "10px"
                  }}
                  onClick={() => {
                    setFormValues(record);
                    handleFileList([{
                      uid:record.id,
                      status: 'done',
                      url:record.img
                    }]);
                    handleModalVisible(true);
                  }}
                >
                  修改
                </Button>
              </Access>
              <Access accessKey={"@approved_del"}>
                <Button
                  type="primary"
                  danger
                  style={{
                    marginLeft: "10px"
                  }}
                  onClick={() => {
                    Modal.confirm({
                      title: '注意',
                      content: '确认要删除此图片吗',
                      onOk() {
                        del(record).then(res=>{
                          if (res?.code === 0)message.success("删除成功")
                          actionRef.current.reload();
                        })
                      },
                      onCancel() {},
                    });
                  }}
                >
                  删除
                </Button>
              </Access>
            </div>
          </>
        );
      },
    },

  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="轮播图列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{x: 1400}}
        bordered
        request={(params, sorter, filter) => getPage({...params, sorter, filter})}
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        toolBarRender={() => [

          <Button
          key="approved_add"
          type="primary"
          onClick={() => {
          formValues.id = null;
          setFormValues(Object.assign(formValues));
          handleModalVisible(true);
        }}
          >
          <PlusOutlined/> 新增
          </Button>
          ,

        ]}

        columns={columns}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
      />
      <CreateForm
        title="轮播图信息"
        onCancel={() => {
          handleModalVisible(false);
        }}
        modalVisible={createModalVisible}
        width={800}
        btn_view={null}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            if (formValues){
              value.id = formValues.id;
            }

            if (fileList.length === 0){
              message.error("请上传图片!");
              return;
            }else if (fileList.length > 1){
              message.error("只能上传一张图片!");
              return;
            }else{
              value.img = fileList[0].url;
            }
            update(value).then(res=>{
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            });
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
            initialValues: formValues
          }}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
